<template>
  <div class="main">
    <div class="topTitle">{{ props.title }}</div>
    <div class="form_content">
      <NScrollbar>
        <div class="content">
          <div class="content_cen">
            <NForm ref="formRef" require-mark-placement="left" label-placement="left" :rules="rules" :label-width="130"
              :model="formValue">
              <NFormItem label="来文标题:" path="titleCommunication">
                <NInput placeholder="请输入来文标题" class="commonWidth" :allow-input="stopNull"
                  v-model:value="formValue.titleCommunication" />
              </NFormItem>
              <NFormItem label="来文单位:" path="unitCommunication">
                <NInput placeholder="请输入来文单位" class="commonWidth" :allow-input="stopNull"
                  v-model:value="formValue.unitCommunication" />
              </NFormItem>
              <NFormItem label="来文文号:" path="noCommunication">
                <NInput placeholder="请输入来文文号" class="commonWidth" :allow-input="stopNull"
                  v-model:value="formValue.noCommunication" />
              </NFormItem>
              <NFormItem label="阅办类型:" path="readTypeCode">
                <NSelect clearable placeholder="请选择阅办类型" class="commonWidth" :options="readingList"
                  v-model:value="formValue.readTypeCode" @update-value="changeType" />
              </NFormItem>
              <NFormItem label="是否加急:" path="isUrgent">
                <NRadioGroup v-model:value="formValue.isUrgent">
                  <NRadio v-for="i in statusList" :key="i.value" :value="i.value">
                    {{ i.label }}
                  </NRadio>
                </NRadioGroup>
              </NFormItem>
              <NFormItem label="附件:" path="fileId">
                <VUpload :file-list="fileList" @getList="handleUploadList" />
              </NFormItem>
            </NForm>
          </div>
        </div>
      </NScrollbar>
    </div>
  </div>
  <FixedAction>
    <div style="display: flex">
      <NSpace justify="start" style="flex: 0 0 42%">
        <NButton style="width: 78px; color: #5fb17f" ghost @click="goBack">
          <template #icon>
            <img :src="VBackImg" style="width: 25rem; height: 25rem" />
          </template>
          返回
        </NButton>
      </NSpace>

      <NSpace justify="center">
        <NButton type="primary" @click="confirm" style="width:78px">
          提交
        </NButton>
      </NSpace>
    </div>
  </FixedAction>

  <NModal :auto-focus="false" v-model:show="modalVisible">
    <VDialogContent @close="modalVisible = false" @submit="againConfirm" title="保存提示" :loading="loading">
      <div style="width: 300rem; height: 100rem; text-align: center; line-height: 100rem">
        您确定要提交申请吗？
      </div>
    </VDialogContent>
  </NModal>
</template>

<script setup lang="ts">
import { ref, reactive, watch } from 'vue'
import {
  NSpace,
  NForm,
  NInput,
  NFormItem,
  NButton,
  NScrollbar,
  useMessage,
  NModal,
  NSelect,
  NRadioGroup,
  NRadio,
  type FormInst
} from 'naive-ui'
import router from '@/router'
import { useTagStore } from '@/stores/layout'
import FixedAction from '@/components/FixedAction.vue'
import { sendRequest } from '@/utils/api'
import VDialogContent from '@/views/OA/Common/DialogContent.vue'
import { useRoute } from 'vue-router'
import VBackImg from '@/assets/images/back.png'
import VUpload from '@/views/OA/Common/Upload.vue'

const route = useRoute()
const tags = useTagStore().tags
const message = useMessage()

const props = defineProps({
  title: { type: String, default: () => '新建阅办任务' },
  id: { type: [Number, String], default: () => null }
})

const formValue = reactive<Record<string, any>>({
  titleCommunication: null,
  unitCommunication: null,
  noCommunication: null,
  readTypeName: null,
  readTypeCode: null,
  isUrgent: null,
  fileId: null
})
const rules = {
  isUrgent: {
    required: true,
    trigger: 'change',
    message: '请选择是否加急'
  },
  titleCommunication: {
    required: true,
    trigger: ['input', 'blur'],
    validator: (_: any, value: any) => {
      if (!value) return new Error('请填写来文标题')
      if (value.length > 100) return new Error('来文标题不得超过100')
      return true
    }
  },
  unitCommunication: {
    required: true,
    trigger: ['input', 'blur'],
    validator: (_: any, value: any) => {
      if (!value) return new Error('请填写来文单位')
      if (value.length > 100) return new Error('来文单位不得超过100')
      return true
    }
  },
  noCommunication: {
    required: false,
    trigger: ['input', 'blur'],
    validator: (_: any, value: any) => {
      if (value?.length > 100) return new Error('来文文号不得超过100')
      return true
    }
  },
}

//去除空格
const stopNull = (value: string) => {
  return !value.startsWith(' ') && !value.endsWith(' ')
}

const readingList = [
  {
    value: '阅办件',
    label: '阅办件'
  },
  {
    value: '阅知件',
    label: '阅知件'
  }
]

const statusList = [
  {
    value: '加急',
    label: '加急'
  },
  {
    value: '不加急',
    label: '不加急'
  }
]

const changeType = (val: any) => {
  formValue.readTypeName = val
}
//获取详情
const fileList: any = ref([])
const getInfo = async () => {
  const [error, res] = await sendRequest({
    module: 'readingandprocessing',
    api: 'Item',
    uri: {
      id: props.id as never
    }
  })
  if (error) return message.error(error.message)
  if (res.code !== 0) return message.error(res.msg)
  Object.keys(formValue).map((it: any) => {
    // @ts-ignore
    formValue[it] = res.data[it]
  })
}
// 返回
const goBack = () => {
  const index = tags.findIndex((item: any) => item.path === router.currentRoute.value.fullPath)
  tags.splice(index, 1)
  if (tags.length == 0) {
    router.push({ path: '/OA/Workbench/UserDesktop' })
  } else history.back()
}
// 附件
const handleUploadList = (v: any) => (formValue.fileId = v)
// 确定
const loading = ref(false)
const formRef = ref<FormInst | null>(null)
const modalVisible = ref(false)

const confirm = () => {
  formRef.value?.validate(async (err) => {
    if (err) return
    modalVisible.value = true
  })
}

const againConfirm = async () => {
  loading.value = true
  if (props.id) {
    const [error, res] = await sendRequest({
      module: 'readingandprocessing',
      api: 'Update',
      override: {
        data: {
          ...formValue.value,
          id: props?.id
        }
      }
    })
    modalVisible.value = false
    goBack()
    if (error) return message.error(error.message)
    if (res.code) return message.error(res.msg)
    message.success(res.msg)
  } else {
    const [error, res] = await sendRequest({
      module: 'readingandprocessing',
      api: 'Save',
      override: {
        data: formValue
      }
    })
    modalVisible.value = false
    goBack()
    if (error) return message.error(error.message)
    if (res.code) return message.error(res.msg)
    message.success(res.msg)
  }
  loading.value = false
}

watch(
  () => props.id,
  () => {
    if (props.title == '编辑阅办任务' && props.id) getInfo()
  },
  { deep: true, immediate: true }
)
</script>

<style scoped lang="scss">
@mixin CommonFont {
  font-size: 16rem;
  font-family: PingFangSC, PingFang SC;
  font-weight: 400;
  color: rgba(0, 0, 0, 0.85);
}

.commonWidth {
  width: 240rem;
}

.main {
  display: flex;
  flex-direction: column;
  width: 100%;
  height: 100%;
  overflow: hidden;

  .topTitle {
    width: 100%;
    border-bottom: 1px solid #fff;
    padding: 15rem 20rem;
    margin-bottom: 20rem;
    @include CommonFont;
  }

  .form_content {
    width: 100%;
    height: 100%;
    padding: 0 20rem 0rem;

    .content {
      display: flex;
      flex-wrap: wrap;
      width: 100%;
      height: 100%;
      padding: 20rem 0 180rem;
      background-color: #ebeceb;

      .scope {
        display: flex;
        flex-wrap: wrap;
        width: 100%;

        .userBox {
          display: flex;
          justify-content: space-between;
          align-items: center;
          width: 100%;
          height: 40rem;
          background-color: #fff;
          border-radius: 4rem;
          padding: 5px 10rem;
          margin-bottom: 10rem;
        }
      }
    }
  }
}

.content_cen {
  display: flex;
  flex-direction: column;
  margin-left: 35%;
}

.iconStyle {
  margin-right: 5rem;
  color: #5fb17f;
}

.progress {
  display: flex;
  align-items: center;
  min-width: 350rem;
  max-width: 800rem;
  min-height: 50rem;
  background-color: #d5e2d8;
  border-radius: 5rem;
  margin-bottom: 10px;
  padding: 5px 15px;
  margin-left: 35%;
}

.progressHint {
  display: flex;
  min-width: 350rem;
  max-width: 800rem;
  padding: 5px 15px;
  margin-left: 35%;
}

.content::-webkit-scrollbar {
  display: none;
}

:deep(.n-spin-container) {
  width: 100%;
  height: 100%;
}

:deep(.n-scrollbar-container) {
  width: 100%;
  height: 100%;
}

:deep(.n-spin-content) {
  width: 100%;
  height: 100%;
}
</style>
